package com.estock.platform.http.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import com.estock.platform.http.request.StockClientRequest;
import com.estock.platform.http.utils.RequestUtil;

public abstract class AbstractURLConnectClient implements ESHttpClient {
	
	protected String contentType;
	protected int responseCode = -1;
	
	protected InputStream getInputStream(StockClientRequest request, 
			Map<String, String> headers, String requestMethod) {
		InputStream inputStream = null;
		URLConnection c = null;
		try {
			URL url = new URL(request.getLocationUri());

			c = url.openConnection();
			if (c instanceof HttpURLConnection) {
				HttpURLConnection httpURLConnection = (HttpURLConnection) c;

				if (headers != null && !headers.isEmpty()) {
					for (Map.Entry<String, String> header : headers.entrySet()) {
						httpURLConnection.addRequestProperty(header.getKey(),
								header.getValue());
					}
				}

				if (!RequestUtil.isEmpty(requestMethod)) {
					httpURLConnection.setRequestMethod(requestMethod);
					if (requestMethod.equals(RequestUtil.HttpMethod.POST)) {
						httpURLConnection.setDoOutput(true);
						OutputStream ost = httpURLConnection.getOutputStream();
						PrintWriter pw = new PrintWriter(ost);
						pw.print(request.getBody());
						pw.flush();
						pw.close();
					}
				} else {
					httpURLConnection
							.setRequestMethod(RequestUtil.HttpMethod.GET);
				}

				httpURLConnection.connect();

				responseCode = httpURLConnection.getResponseCode();
				if (responseCode == 400) {
					inputStream = httpURLConnection.getErrorStream();
				} else {
					inputStream = httpURLConnection.getInputStream();
				}
				
				contentType = c.getContentType();
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		
		return inputStream;
	}
	
}
